/**
 * @file dify.js
 * @description Dify API 调用工具函数
 * @created 2024-07-29
 */

const DIFY_API_KEY = 'app-zWTMgCLb1yICdF0Vv1JE8E1S';
const DIFY_BASE_URL = 'http://121.40.242.43/v1';

/**
 * 发送消息到 Dify AI 并获取流式响应
 * @param {string} query - 用户输入/提问内容
 * @param {string} user - 用户标识
 * @param {string} conversationId - (可选) 会话 ID
 * @param {function} onStreamData - 处理流式数据的回调函数 (接收解析后的 JSON data)
 * @param {function} onStreamEnd - 流式响应结束的回调函数
 * @param {function} onError - 发生错误时的回调函数 (接收 Error 对象)
 * @returns {Promise<void>}
 */
export async function sendMessageToDifyStream(query, user, conversationId, onStreamData, onStreamEnd, onError) {
  const url = `${DIFY_BASE_URL}/chat-messages`;
  const headers = {
    'Authorization': `Bearer ${DIFY_API_KEY}`,
    'Content-Type': 'application/json',
  };
  const body = {
    query,
    user,
    response_mode: 'streaming',
    inputs: {}, // 根据您的 Dify 应用配置，可能需要传入特定变量
    auto_generate_name: true, // 可以根据需要设置为 false
  };

  if (conversationId) {
    body.conversation_id = conversationId;
  }

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers,
      body: JSON.stringify(body),
    });

    if (!response.ok) {
      let errorData;
      try {
        errorData = await response.json();
      } catch (e) {
        // If response is not JSON, use text
        errorData = { message: await response.text() };
      }
      console.error('Dify API Error Response:', errorData);
      if (onError) {
        onError(new Error(`API request failed with status ${response.status}: ${errorData.message || 'Unknown error'}`));
      }
      return;
    }

    if (!response.body) {
      if (onError) {
        onError(new Error('Response body is null'));
      }
      return;
    }

    const reader = response.body.getReader();
    const decoder = new TextDecoder('utf-8');
    let buffer = '';
    let currentConversationId = conversationId;

    // eslint-disable-next-line no-constant-condition
    while (true) {
      const { done, value } = await reader.read();
      if (done) {
        if (onStreamEnd) {
          onStreamEnd(currentConversationId); // Pass back the latest conversation ID
        }
        break;
      }

      buffer += decoder.decode(value, { stream: true });
      
      // SSE events are separated by double newlines.
      let eventEndIndex;
      while ((eventEndIndex = buffer.indexOf('\n\n')) !== -1) {
        const eventString = buffer.substring(0, eventEndIndex);
        buffer = buffer.substring(eventEndIndex + 2); // Skip the double newline separator

        if (eventString.startsWith('data:')) {
          const jsonDataString = eventString.substring(5).trim();
          if (jsonDataString) {
            try {
              const jsonData = JSON.parse(jsonDataString);
              if (jsonData.conversation_id) {
                currentConversationId = jsonData.conversation_id; // Update conversationId from stream
              }
              if (onStreamData) {
                // Pass the raw JSON data from the event
                onStreamData(jsonData); 
              }
            } catch (e) {
              console.error('Error parsing SSE event JSON:', e, 'Event JSON String:', jsonDataString);
              // Potentially handle malformed JSON or skip
            }
          }
        }
      }
    }
  } catch (error) {
    console.error('Error sending message to Dify:', error);
    if (onError) {
      onError(error);
    }
  }
}

/**
 * 上传文件到 Dify
 * @param {File} file - 要上传的文件
 * @param {string} user - 用户标识
 * @returns {Promise<object|null>} 上传成功返回文件信息，失败返回 null
 */
export async function uploadFileToDify(file, user) {
  const url = `${DIFY_BASE_URL}/files/upload`;
  const headers = {
    'Authorization': `Bearer ${DIFY_API_KEY}`,
  };
  const formData = new FormData();
  formData.append('file', file);
  formData.append('user', user);

  try {
    const response = await fetch(url, {
      method: 'POST',
      headers,
      body: formData,
    });

    if (!response.ok) {
      const errorData = await response.json();
      console.error('Dify File Upload API Error:', errorData);
      return null;
    }
    return await response.json();
  } catch (error) {
    console.error('Error uploading file to Dify:', error);
    return null;
  }
}

// 可以在这里添加 Dify API 文档中提到的其他接口的封装，例如：
// - 会话重命名
// - 获取会话列表
// - 获取会话历史消息等 